#include "common/common.h"

struct my_file{
    char name[50];
    uint64_t size;
    char buff[4096];
};

const int MAXLINE = 1024;

void send_file(int fd, char* name, uint64_t size){
    uint64_t cur = 0;
    struct my_file file;
    bzero(&file, sizeof(file));
    strcpy(file.name, name);
    file.size = size;
    FILE *fp = fopen(name, "r");
    if(fp == NULL){
        perror("fopen");
        exit(1);
    }
    uint64_t count = 0;
    while(cur < size){
        if(size - cur < 4096){
            count = size - cur;
        }else{
            count = 4096;
        }
        
        int num = fread(&file.buff, 1, count, fp);
        cur += num;
        DBG(GREEN"total is %lu, have read %lu, this time read %d\n"NONE, size, cur, num);
        if(send(fd, &file, sizeof(file), 0) < 0){
            perror("send");
            exit(1);
        }
    }
}


int main(int argc, char** argv){
    int opt;
    char ip[20] = "123.57.102.65";
    int port = 9004;
    char name[50] = {0};
    uint64_t size = 0;

    if(argc != 3){
        fprintf(stderr, "Usage : %s -n filename\n", argv[0]);
        exit(1);
    }
    while((opt = getopt(argc, argv, "n:")) != -1){
        switch(opt){
            case 'n':
                strcpy(name, optarg);
                break;
            default:
                fprintf(stderr, "Usage : %s -p port\n", argv[0]);
                exit(1);
        }
    }

    int confd = connect_host(ip, port);
    if(confd < 0){
        perror("connect_host");
        exit(1);
    }

    FILE *fp = fopen(name, "r");
    if(fp == NULL){
        perror("fopen");
        exit(1);
    }
    int fd = fileno(fp);
    size = lseek(fd, 0, SEEK_END);
    DBG(GREEN"the file size is %lu\n"NONE, size);
    send_file(confd, name, size);

    return 0;
}
